<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch" label-width="68px">
      <el-row>
        <el-col :span="4" v-show="false">
          <el-form-item label="产品信息" prop="itemId">
            <el-input v-model="queryParams.itemId" placeholder="请选择产品信息" disabled ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="产品信息" prop="itemCode">
            <el-input v-model="queryParams.itemCode" placeholder="请选择产品信息" disabled >
              <el-button slot="append" icon="el-icon-search" @click="openSelectItemQuery = true"></el-button>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="工厂" prop="factoryId">
            <selectFactory v-model="queryParams.factoryId"></selectFactory>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="生产车间" prop="workshopId">
            <selectWorkshop v-model="queryParams.workshopId"></selectWorkshop>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['mes:item-produce:create']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
                   v-hasPermi="['mes:item-produce:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="工厂" align="center" prop="factoryName" />
      <el-table-column label="生产车间" align="center" prop="workshopName" />
      <el-table-column label="产品名称" align="center" prop="itemName" />
      <el-table-column label="产品代码" align="center" prop="itemCode" />
      <el-table-column label="产品规格" align="center" prop="spec" />
      <el-table-column label="产品图号" align="center" prop="drawCode" />
      <el-table-column label="质检模式" align="center" prop="qualityType">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.QUALITY_TYPE" :value="scope.row.qualityType" />
        </template>
      </el-table-column>
      <el-table-column label="领料模式" align="center" prop="pickingType">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.PICKING_TYPE" :value="scope.row.pickingType" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['mes:item-produce:update']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['mes:item-produce:delete']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="1400px" v-dialogDrag append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="产品名称" prop="itemName">
              <el-input v-model="form.itemName" placeholder="请选择产品" disabled >
                <el-button slot="append" icon="el-icon-search" @click="openSelectItem = true"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品代码" prop="itemCode">
              <el-input v-model="form.itemCode" placeholder="" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品图号" prop="drawCode">
              <el-input v-model="form.drawCode" placeholder="" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="产品规格" prop="spec">
              <el-input v-model="form.spec" placeholder="" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工厂" prop="factoryId">
              <selectFactory v-model="form.factoryId"></selectFactory>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生产车间" prop="workshopId">
              <selectWorkshop v-model="form.workshopId"></selectWorkshop>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="质检模式" prop="qualityType">
              <el-select v-model="form.qualityType" placeholder="请选择质检模式">
                <el-option v-for="dict in this.getDictDatas(DICT_TYPE.QUALITY_TYPE)"
                           :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="领料模式" prop="pickingType">
              <el-select v-model="form.pickingType" placeholder="请选择领料模式">
                <el-option v-for="dict in this.getDictDatas(DICT_TYPE.PICKING_TYPE)"
                           :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="工艺路线" prop="pickingType">
              <el-button type="primary" @click="openSelectProcessRoute = true">添加</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-tabs type="border-card" v-model="tabActivity" closable @tab-remove="removeProcessRoute">
              <el-tab-pane v-for="(item) in form.routeList" :key="item.routeId" :label="item.routeName" :name="item.routeCode" >
                <el-descriptions title="路线信息">
                  <el-descriptions-item label="路线名称">{{item.routeName}}</el-descriptions-item>
                  <el-descriptions-item label="路线代码">{{item.routeCode}}</el-descriptions-item>
                  <el-descriptions-item label="是否默认">
                    <el-radio-group v-model="item.defaultRoute">
                      <el-radio v-for="dict in defaultRouteOptions"
                                :key="dict.value" :label="parseInt(dict.value)">{{dict.label}}</el-radio>
                    </el-radio-group>
                  </el-descriptions-item>
                </el-descriptions>
                <el-table :data="item.extendList" stripe style="width: 100%">
                  <el-table-column label="当前工序" align="center" prop="processId">
                    <template slot-scope="scope">
                      <el-select v-model="scope.row.processId" placeholder="请选择工序" disabled>
                        <el-option
                          v-for="item in processOptions"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                        />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="下道工序" align="center" prop="nextProcessId">
                    <template slot-scope="scope">
                      <el-select v-model="scope.row.nextProcessId" placeholder="无" disabled>
                        <el-option
                          v-for="item in processOptions"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                        />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="与下道工序关系" align="center" prop="link">
                    <template slot-scope="scope">
                      <el-select v-model="scope.row.link" placeholder="请选择" disabled>
                        <el-option v-for="dict in linkOptions"
                                   :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
                      </el-select>
                      <el-tooltip content="NO：当前工序与下道工序没有关联关系；E-S：当前工序报工完成，下道工序才允许报工" placement="top">
                        <i class="el-icon-question"></i>
                      </el-tooltip>
                    </template>
                  </el-table-column>
                  <el-table-column label="是否为关键工序" align="center" prop="mainProcess">
                    <template slot-scope="scope">
                      <el-select v-model="scope.row.mainProcess" placeholder="请选择" disabled>
                        <el-option v-for="dict in mainProcessOptions"
                                     :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"/>
                      </el-select>
                      <el-tooltip content="关键工序会改变工单已报工数量" placement="top">
                        <i class="el-icon-question"></i>
                      </el-tooltip>
                    </template>
                  </el-table-column>
                  <el-table-column label="工时" align="center" prop="workHours">
                    <template slot-scope="scope">
                      <el-input type="number" v-model="scope.row.workHours" placeholder="工时"></el-input>
                    </template>
                  </el-table-column>
                  </el-table>
              </el-tab-pane>
            </el-tabs>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 选择产品组件（增加修改界面） -->
    <selectItem :openSelectItem.sync='openSelectItem' @selectItem='selectItem'></selectItem>
    <!-- 选择产品组件（查询界面） -->
    <selectItem :openSelectItem.sync='openSelectItemQuery' @selectItem='selectItemQuery'></selectItem>
    <selectProcessRoute :openSelectProcessRoute.sync='openSelectProcessRoute' :factory='form.factoryId' @selectProcessRoute="selectProcessRoute"></selectProcessRoute>
  </div>
</template>

<script>
import { createItemProduce, updateItemProduce, deleteItemProduce, getItemProduce, getItemProduceInfo, getItemProducePage, exportItemProduceExcel } from "@/api/mes/itemProduce";
import { getProcessSimple } from '@/api/mes/process'
import SelectFactory from "@/components/SelectFactory"
import SelectItem from "@/components/SelectItem"
import SelectProcessRoute from "@/components/SelectProcessRoute"
import SelectWorkshop from '@/components/SelectWorkshop/index.vue'

export default {
  name: "ItemProduce",
  components: {
    SelectFactory,
    SelectItem,
    SelectWorkshop,
    SelectProcessRoute
  },
  data() {
    return {
      tabActivity: undefined,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品生产信息列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 打开选择产品组件(查询使用)
      openSelectItemQuery:false,
      // 打开选择产品组件
      openSelectItem:false,
      // 打开选择工艺路线组件
      openSelectProcessRoute: false,
      // 默认路线字典
      defaultRouteOptions: [],
      // 工序列表
      processOptions: [],
      // 主要工序选项
      mainProcessOptions: [],
      // 工序关系选项
      linkOptions: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        factoryId: null,
        workshopId: null,
        itemId: null,
        itemCode: null,
        qualityType: null,
        pickingType: null,
        createTime: [],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        factoryId: [{ required: true, message: "工厂不能为空", trigger: "blur" }],
        workshopId: [{ required: true, message: "生产车间不能为空", trigger: "blur" }],
        itemId: [{ required: true, message: "产品信息不能为空", trigger: "blur" }],
        qualityType: [{ required: true, message: "质检模式不能为空", trigger: "change" }],
        pickingType: [{ required: true, message: "领料模式不能为空", trigger: "change" }],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getItemProducePage(this.queryParams).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 获取字典 */
    getDict() {
      this.defaultRouteOptions = this.getDictDatas(this.DICT_TYPE.SYSTEM_INTEGER_STATUS)
      this.linkOptions = this.getDictDatas(this.DICT_TYPE.MES_PROCESS_LINK);
      this.mainProcessOptions = this.getDictDatas(this.DICT_TYPE.SYSTEM_INTEGER_STATUS)
    },
    /** 查询工序选项列表 */
    getProcessSimpleFun(factoryId){
      const queryParam = {
        factoryId: factoryId,
        status: 0
      }
      getProcessSimple(queryParam).then(response => {
        this.processOptions = response.data
      })
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        factoryId: undefined,
        workshopId: undefined,
        itemId: undefined,
        itemName: undefined,
        itemCode: undefined,
        spec: undefined,
        drawCode: undefined,
        remark: undefined,
        qualityType: undefined,
        pickingType: undefined,
        routeList: [],
      };
      this.resetForm("form");
    },
    /** 产品选择回调事件 */
    selectItem(item){
      this.form.itemId = item.id;
      this.form.itemCode = item.code;
      this.form.itemName = item.name;
      this.form.spec = item.spec;
      this.form.drawCode = item.drawCode;
      this.form.remark = item.remark;
    },
    /** 产品选择回调事件(查询使用) */
    selectItemQuery(item){
      this.queryParams.itemId = item.id;
      this.queryParams.itemCode = item.code;
    },
    /** 移除工艺路线 */
    removeProcessRoute(data) {
      const index = this.form.routeList.findIndex(obj => obj.routeCode == data);
      this.form.routeList.splice(index, 1);
      this.changeTabActivity();
    },
    /** 选择产品工艺路线 */
    selectProcessRoute(data) {
      //如果已经存在，直接返回
      if(this.form.routeList.find(obj => obj.routeId == data.id)){
        return;
      }
      const route = {
        itemProduceId: undefined,
        routeId: data.id,
        routeCode: data.code,
        routeName: data.name,
        defaultRoute: 0,
        extendList: []
      };
      for(let i =0; i<data.routeInfo.length; i++) {
        let item = data.routeInfo[i]
        const routeInfo = {
          routeInfoId: item.id,
          processId: item.processId,
          nextProcessId: item.nextProcessId,
          link: item.link,
          mainProcess: item.mainProcess,
          workHours: item.workHours
        };
        route.extendList.push(routeInfo);
      }
      this.form.routeList.push(route)
      this.changeTabActivity()

    },
    /** 改变tab活跃页 */
    changeTabActivity(){
      this.tabActivity = this.form.routeList.length>0?this.form.routeList[this.form.routeList.length -1].routeCode:undefined
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加产品生产信息";
      this.getDict();
      this.changeTabActivity()
      this.getProcessSimpleFun(this.form.factoryId)

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getItemProduceInfo(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改产品生产信息";
        this.getProcessSimpleFun(this.form.factoryId)
        this.changeTabActivity()
      });
      this.getDict();

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          updateItemProduce(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createItemProduce(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除产品生产信息编号为"' + id + '"的数据项?').then(function() {
          return deleteItemProduce(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal.confirm('是否确认导出所有产品生产信息数据项?').then(() => {
          this.exportLoading = true;
          return exportItemProduceExcel(params);
        }).then(response => {
          this.$download.excel(response, '产品生产信息.xls');
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
